package com.xjoyt.pay.share.api.sms;

import java.security.MessageDigest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.share.dto.PhoneCodeResult;
import com.xjoyt.pay.share.params.PhoneCodeParam;

import feign.Feign;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;

@Component
public class SmsBaoClient {

	private static final String API_URL = "http://api.smsbao.com";

	@Value("${sms.bao.account}")
	private String account;

	@Value("${sms.bao.password}")
	private String password;

	public ExecuteResult<PhoneCodeResult> sendCode(PhoneCodeParam param, String code) throws Exception {
		if (StringUtils.isBlank(param.phone)) {
			return null;
		}
		String content = String.format("您的验证码为：%s", code);
		boolean success = send(param.phone, content, param.sign);
		if (!success) {
			return ExecuteResult.fail();
		}
		PhoneCodeResult result = new PhoneCodeResult();
		result.content = content;
		result.value = code;
		return ExecuteResult.ok(result);
	}

	private boolean send(String phone, String content, String sign) throws Exception {
		SmsBaoContract client = Feign.builder().encoder(new GsonEncoder()).decoder(new GsonDecoder())
				.target(SmsBaoContract.class, API_URL);
		String pwd = encodeMd5(password);
		int send = client.send(account, pwd, phone, String.format("【%s】%s", sign, content));
		return send == 0;
	}

	private String encodeMd5(String msg) throws Exception {
		MessageDigest md = MessageDigest.getInstance("MD5");
		String resultString = byteArrayToHexString(md.digest(msg.getBytes("UTF-8")));
		return resultString.toUpperCase();
	}

	private String byteArrayToHexString(byte[] bytes) {
		String hs = StringUtils.EMPTY;
		String stmp = StringUtils.EMPTY;
		for (int n = 0; n < bytes.length; n++) {
			stmp = java.lang.Integer.toHexString(bytes[n] & 0XFF);
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs;
	}

}
